package org.amj.srt;

import java.util.ArrayList;
import java.util.List;

public class SrtEntry {
	private final Srt srt;
	private final SrtTimeEntry start;
	private final SrtTimeEntry end;
	private String text;


	SrtEntry(Srt srt) {
		this.srt = srt;
		start = new SrtTimeEntry(this);
		end = new SrtTimeEntry(this);
	}


	public SrtTimeEntry getStart() {
		return start;
	}

	public SrtTimeEntry getEnd() {
		return end;
	}

	public String getText() {
		return text;
	}


	public void setText(String text) {
		this.text = text;
	}


	public String toSrtEntry(int index) {
		return index + "\r\n" +
				start.toSrtEntry() + " --> " + end.toSrtEntry() + "\r\n" +
				text + "\r\n\r\n";

	}


	public void shift(int seconds) {
		start.shift(seconds);
		end.shift(seconds);
	}


	public void shortenEntry(int charCount) {
		if(charCount >= text.length()) {
			return;
		}
		
		List<String> lines = lines(charCount);
		
		this.setText(lines.get(0));
		
		int c = lines.size();
		
		float diff = (end.getTotalSecond() - start.getTotalSecond());
		float segment = diff/c;
		end.shift(-((int)Math.ceil(diff)));
		end.shift(((int)Math.floor(segment)));
		
		List<SrtEntry> newEntries = new ArrayList<SrtEntry>();
		
		for(int i = 1; i < lines.size(); i++) {
			SrtEntry newEntry = srt.newEntry(start.getHour(), start.getMinute(), 
					start.getSecond(), start.getMilli(), 
					end.getHour(), end.getMinute(), end.getSecond(), 
					end.getMilli(), lines.get(i));
			
			newEntry.shift(((int)Math.floor(segment* i)));
			
			newEntries.add(newEntry);
		}
		
		srt.getEntries().addAll(srt.getEntries().indexOf(this) + 1, newEntries);
		
		
	}

	private List<String> lines(int charCount) {
		List<String> parts = new ArrayList<String>();
		if(charCount >= text.length()) {
			parts.add(text);
		} else {

			String string = text;
			int n = charCount;
			while (true) {
				// look for space to the left of n-th character
				int index = string.lastIndexOf(" ", n);
				if (index == -1) {
					// no space to the left (very long word) -> next space to the right
					// change this to 'index = n' to break words in this case
					index = string.indexOf(" ", n);
				}
				if (index == -1) {
					break;
				}
				parts.add(string.substring(0,  index));
				string = string.substring(index+1);
			}
			parts.add(string);
		}
		
		if(parts.size() > 1) {
			parts.set(parts.size() - 2, parts.get(parts.size() - 2) + " " + parts.get(parts.size() - 1));
			parts.remove(parts.size() - 1);
		}
		return parts;
	}


	@Override
	public String toString() {
		return "SrtEntry [start=" + start + ", end=" + end + ", text=" + text
				+ "]";
	}
	
	

}
